package cn.jxau.fukin.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class AuthorityInterceptor implements HandlerInterceptor {
	// 进入handler方法之前执行
	// 用于身份认证和身份授权
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		System.out.println("this is AuthorityInterceptor");
		// 返回false表示拦截住,不再往下放行,return true表示继续执行
		String uri = request.getRequestURI();

		String[] chains = { "login.do" };// 所有放行的路径
		for (String chain : chains) {
			if (uri.indexOf(chain) != -1) {
				return true;
			}
		}
		HttpSession session = request.getSession();
		if (session == null || session.getAttribute("user") == null) {
			request.setAttribute("MSG", "你还没有登入，请登入!");
			request.getRequestDispatcher("/login.jsp").forward(request, response);
			// response.sendRedirect(request.getContextPath() +
			// "/user/showLoginPage.do");
			return false;
		}
		return true;
	}

	// 进入handler方法之后,在返回ModelAndView之前执行
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler, ModelAndView modelAndView) throws Exception {
		// 应用场景从ModelAndView出发:将公用的模型数据,在这里传到视图,也可以在此统一指定视图
		// 比如,菜单的导航,每个视图菜单的内容都是一样的,可以再此统一指定
		System.out.println("HandlerInterceptor1..postHandle");
	}

	// 执行handler之后执行此方法
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
			Object handler, Exception ex) throws Exception {
		// 统一的异常处理
		// 统一的日志处理
		System.out.println("HandlerInterceptor1..afterCompletion");
	}
}